<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

include_once('../arc2-starter-pack/config.php');
$store = ARC2::getStore($arc_config);

$output = array();

$q = "
prefix dct:<http://purl.org/dc/terms/>
prefix xsd:<http://www.w3.org/2001/XMLSchema#>
prefix foaf: <http://xmlns.com/foaf/0.1/>
select distinct ?uri ?name count(?paper) as ?c where {
	?uri foaf:name ?name .
	?paper dct:creator ?uri .
	filter regex(?name, '".$_GET["s"]."', 'i') .
}
group by ?uri
order by desc(?c)
";

$rows = $store->query($q, 'rows');

foreach ($rows as $row) {
	$uri = $row["uri"];
	$name = $row["name"];
	$count = $row["c"];

	if (isset($output[$uri])) {
		if (strlen($output[$uri]["name"]) < strlen($name)) {
			$output[$uri]["name"] = $name;
		}
	}
	else {
		$person = array();
		$person["count"] = $count;
		$person["name"] = $name;
		$output[$uri] = $person;
		
	}
}

# output as json
header('Content-type: text/plain');

echo "<table>";
foreach ($output as $uri => $person) {
	$url = "pivot.php?uri=".$uri;
	$pubText = " publications";
	if ($person["count"] == 1) {
		$pubText = " publication";
	}
	echo "<tr><td class='searchName'><a href='".$url."'>".$person["name"]."</a></td><td class='searchCount'> ".$person["count"]. $pubText ."</td></tr>";
}
echo "</table>";

?>
